﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using Aspose.Cells;
using CuteSprite.Eme.Client;
using CuteSprite.Eme.Data;
using CuteSprite.Eme.Data.BsdUserCenter;
using CuteSprite.Eme.MIS.Client;
using CuteSprite.Eme.UI.BsdUserCenter.Resources;
using CuteSprite.Eme.UI.Utils;
using HmFramework.Components;
using HmFramework.Data;
using HmFramework.IO;
using HmFramework.UI.Utils;

namespace CuteSprite.Eme.UI.BsdUserCenter
{
	public partial class FrmExportCustomer : EmeEntityAdminForm
	{
		/// <summary>开发票情况</summary>
		private enum InvoiceSituation : int
		{
			是 = 1,
			否 = 2,
			无需开发票 = 3
		}

		#region -- 属性 --

		private Int32 _SelectCustomer;

		private EntityList<BsdStaff> _StaffList = null;

		/// <summary>缓存员工表</summary>
		private EntityList<BsdStaff> StaffList
		{
			get
			{
				if (_StaffList == null)
				{
					try
					{
						// 只获取显示字段和值字段
						var cache = EmeRemotingHelper.FindEntityList(EntityHelper.ModelUserCenter, EntityHelper.UserCenterTableStaff,
								null, null, "ID,FullName", 0, 0, false, null, false);
						if (cache != null)
						{
							_StaffList = cache.FindAll() as EntityList<BsdStaff>;
						}
						else
						{
							_StaffList = new EntityList<BsdStaff>();
						}
					}
					catch (Exception ex) { DialogHelper.ShowWarning(null, ex.Message); }
				}
				return _StaffList;
			}

			//set { _StaffTable = value; }
		}

		private EntityList<BsdCustomer> _CustomerList = null;

		/// <summary>缓存客户表</summary>
		private EntityList<BsdCustomer> CustomerList
		{
			get
			{
				if (_CustomerList == null)
				{
					try
					{
						var factory = EmeEntityFactory.Create(EntityHelper.ModelUserCenter, EntityHelper.UserCenterTableCustomer);
						//var exp = CurrentEntityFactory.MakeEqual(BsdCustomer._.OrganizeID, SelectCustomer);
						// 只获取显示字段和值字段
						var cache = EmeRemotingHelper.FindEntityList(EntityHelper.ModelUserCenter, EntityHelper.UserCenterTableCustomer,
								null, factory.MakeOrder(BsdCustomer.___.OrganizeID), null, 0, 0, false, null, false);
						if (cache != null)
						{
							_CustomerList = cache.FindAll() as EntityList<BsdCustomer>;
						}
						else
						{
							_CustomerList = new EntityList<BsdCustomer>();
						}

					}
					catch (Exception ex) { DialogHelper.ShowWarning(null, ex.Message); }
				}
				return _CustomerList;
			}

			//set { _CustomerTable = value; }
		}

		/// <summary>缓存部门表</summary>
		private EntityList<BsdOrganize> _OrganizeList = null;

		private EntityList<BsdOrganize> OrganizeList
		{
			get
			{
				if (_OrganizeList == null)
				{
					try
					{
						//var exp = CurrentEntityFactory.MakeNotEqual(BsdOrganize._.FullName, "总经办");
						//var exp2 = CurrentEntityFactory.MakeNotEqual(BsdOrganize._.FullName, "市场营销部");
						//var exp3 = CurrentEntityFactory.MakeNotEqual(BsdOrganize._.FullName, "综合部");
						// 只获取显示字段和值字段
						var factory = EmeEntityFactory.Create(EntityHelper.ModelUserCenter, EntityHelper.UserCenterTableOrganize);
						var selFields = factory.FormatNames(new String[] { "ID", "ParentID", "Code", "FullName" });
						var cache = EmeRemotingHelper.FindEntityList(EntityHelper.ModelUserCenter, EntityHelper.UserCenterTableOrganize,
								null, factory.MakeOrder(BsdOrganize.___.FullName), selFields, 0, 0, false, null, false);
						if (cache != null)
						{
							var entities = cache.FindAll() as EntityList<BsdOrganize>;
							var org = entities.Find(o => o.FullName == "总经办");
							var org1 = entities.Find(o => o.FullName == "市场营销部");
							var org2 = entities.Find(o => o.FullName == "综合部");
							_OrganizeList = entities.FindAll(o => (o.ParentID == org.ID && !(o.FullName.Equals("市场营销部") || o.FullName.Equals("综合部")))
																										|| o.ParentID == org1.ID
																										|| o.ParentID == org2.ID);
						}
						else
						{
							_OrganizeList = new EntityList<BsdOrganize>();
						}
					}
					catch (Exception ex) { DialogHelper.ShowWarning(null, ex.Message); }
				}
				return _OrganizeList;
			}

			//set { _OrganizeTable = value; }
		}

		private EntityList<CustomerContact> _CustomerContactTable = null;

		/// <summary>缓存客户联系人</summary>
		private EntityList<CustomerContact> CustomerContactList
		{
			get
			{
				if (_CustomerContactTable == null)
				{
					try
					{
						var factory = EmeEntityFactory.Create(EntityHelper.ModelUserCenter, EntityHelper.UserCenterTableOrganize);
						var selFields = factory.FormatNames(new String[] { "ID", "CustomerID", "Name", "ContactType", "Telephone", "Email" });
						var exp = factory.MakeEqual(CustomerContact._.ContactType, "客户经办人") | factory.MakeEqual(CustomerContact._.ContactType, "财务");

						// 只获取显示字段和值字段
						var cache = EmeRemotingHelper.FindEntityList(EntityHelper.ModelUserCenter, EntityHelper.UserCenterTableCustomerContact,
								exp, null, selFields, 0, 0, false, null, false);
						if (cache != null)
						{
							_CustomerContactTable = cache.FindAll() as EntityList<CustomerContact>;
						}
						else
						{
							_CustomerContactTable = new EntityList<CustomerContact>();
						}
					}
					catch (Exception ex) { DialogHelper.ShowWarning(null, ex.Message); }
				}
				return _CustomerContactTable;
			}

			//set { _CustomerContact = value; }
		}

		//private FrmExpressAdmin _ExpressAdminForm;

		///// <summary>运单管理窗体</summary>
		//[Browsable(false)]
		//protected FrmExpressAdmin ExpressAdminForm
		//{
		//	get { return _ExpressAdminForm; }
		//	set { _ExpressAdminForm = value; }
		//}

		private EmeBsdMisManagement _BsdMisManagement = null;

		/// <summary>BsdMIS客户端管理</summary>
		protected EmeBsdMisManagement BsdMisManagement
		{
			get
			{
				if (_BsdMisManagement == null) { _BsdMisManagement = ServerManagement as EmeBsdMisManagement; }
				return _BsdMisManagement;
			}
		}

		#endregion

		#region -- 构造 --

		/// <summary>默认构造函数</summary>
		public FrmExportCustomer()
		{
			InitializeComponent();

			InitForm();
		}

		#endregion

		#region -- 窗体事件 --

		protected override void InitComponent()
		{
			base.InitComponent();
		}

		public override void FormOnLoad()
		{
			base.FormOnLoad();

			frmcustomer.DataSource = null;
			frmcustomer.DisplayMember = BsdOrganize.__.FullName;
			frmcustomer.ValueMember = BsdOrganize.__.ID;
			BsdOrganize organize = new BsdOrganize();
			organize.FullName = "-- 请选择 --";
			OrganizeList.Insert(0, organize);
			frmcustomer.DataSource = OrganizeList;
			frmcustomer.SelectedValue = 0;
		}

		#endregion

		#region -- 控件事件 --

		#endregion

		#region -- 辅助 --

		//#region - method BindSystemOptionComboBox -

		///// <summary>绑定下拉列表</summary>
		///// <param name="ctlComboBox"></param>
		///// <param name="tableName"></param>
		///// <remarks>从EmeEntityFormBase窗体复制而来，不需要修改</remarks>
		//protected void BindSystemOptionComboBox(ComboBox ctlComboBox, String tableName)
		//{
		//	if (tableName.IsNullOrWhiteSpace()) { return; }
		//	try
		//	{
		//		ctlComboBox.DataSource = null;
		//		var tbOption = EmeRemotingHelper.MisServerManagement.OptionInfo.GetTable(tableName).Copy();
		//		tbOption.Columns.Add("Name", typeof(String));
		//		foreach (DataRow row in tbOption.Rows)
		//		{
		//			row["name"] = row[SystemOptionInfo._.Column_Item_Value];
		//		}
		//		var drEmpty = tbOption.NewRow();
		//		drEmpty["name"] = "-- 请选择 --";
		//		drEmpty[SystemOptionInfo._.Column_Item_Value] = String.Empty;
		//		tbOption.Rows.InsertAt(drEmpty, 0);
		//		var viewOption = tbOption.DefaultView;
		//		viewOption.Sort = SystemOptionInfo._.Column_Item_SortCode + " Asc";
		//		ctlComboBox.DisplayMember = "name";
		//		ctlComboBox.ValueMember = SystemOptionInfo._.Column_Item_Value;
		//		ctlComboBox.DataSource = viewOption;
		//	}
		//	catch { }
		//}

		//#endregion

		#endregion

		#region -- 导出 --

		/// <summary>
		/// 导出
		/// </summary>
		/// <param name="filename">文件名</param>
		/// <param name="Path">保存地址</param>
		private void Export(string filename, String Path)
		{
			var file = "{0}_{1:yyyy_MM_dd_HH_mm_ss}.xls".FormatWith(filename, DateTime.Now);
			var sourceBook = new Workbook(ResManager.GetFile("客户表.xls"));
			var sourceSheet = sourceBook.Worksheets[0];
			var filter = sourceSheet.AutoFilter;
			filter.AddFilter(0, null);
			var cells = sourceSheet.Cells;

			List<Style> cellStyles = new List<Style>();
			for (Int32 i = 0; i < 23; i++)
			{
				var style = cells[3, i].GetStyle();
				cellStyles.Add(style);
			}
			var id = 1;
			var rowIndex = 3;

			var clist = (SelectCustomer == 0) ? CustomerList : CustomerList.FindAll(c => c.OrganizeID == SelectCustomer);
			if (clist != null && clist.Count > 0)
			{
				foreach (BsdCustomer customer in clist)
				{
					cells[rowIndex, 0].PutValue(id);
					cells[rowIndex, 0].SetStyle(cellStyles[0]);

					///获取所属部门
					foreach (BsdOrganize organize in OrganizeList)
					{
						if (organize.ID == 0) { continue; }
						var organizeid = Convert.ToInt32(customer.OrganizeID);
						if (Convert.ToInt32(organize.ID) == organizeid)
						{
							cells[rowIndex, 1].PutValue(organize.FullName);
							cells[rowIndex, 1].SetStyle(cellStyles[1]);
						}
					}
					cells[rowIndex, 2].PutValue(customer.Code);
					cells[rowIndex, 2].SetStyle(cellStyles[2]);

					///客户名称
					var CompanyName = "";
					CompanyName = customer.NameEN.IsNullOrWhiteSpace() ? customer.Name : customer.Name + customer.NameEN;

					cells[rowIndex, 3].PutValue(CompanyName);
					cells[rowIndex, 3].SetStyle(cellStyles[3]);
					cells[rowIndex, 4].PutValue(customer.Address);
					cells[rowIndex, 4].SetStyle(cellStyles[4]);
					cells[rowIndex, 5].PutValue(customer.OtherAddress);
					cells[rowIndex, 5].SetStyle(cellStyles[5]);
					cells[rowIndex, 6].PutValue("");
					cells[rowIndex, 6].SetStyle(cellStyles[6]);
					var list = CustomerContactList.FindAll(cc => cc.CustomerID == customer.ID && cc.ContactType.Equals("客户经办人"));
					if (list != null && list.Count > 0)
					{
						var contact = list[0] as CustomerContact;
						cells[rowIndex, 7].PutValue(contact.Name);
						cells[rowIndex, 7].SetStyle(cellStyles[7]);
						cells[rowIndex, 8].PutValue(contact.Telephone);
						cells[rowIndex, 8].SetStyle(cellStyles[8]);
						cells[rowIndex, 9].PutValue(contact.Email);
						cells[rowIndex, 9].SetStyle(cellStyles[9]);
					}
					else
					{
						cells[rowIndex, 7].PutValue(customer.Contact);
						cells[rowIndex, 7].SetStyle(cellStyles[7]);
						cells[rowIndex, 8].PutValue(customer.Telephone);
						cells[rowIndex, 8].SetStyle(cellStyles[8]);
						cells[rowIndex, 9].PutValue(customer.Email);
						cells[rowIndex, 9].SetStyle(cellStyles[9]);
					}
					cells[rowIndex, 10].PutValue(customer.Fax);
					cells[rowIndex, 10].SetStyle(cellStyles[10]);
					var list_Finance = CustomerContactList.FindAll(cc => cc.CustomerID == customer.ID && cc.ContactType.Equals("财务"));
					if (list_Finance != null && list_Finance.Count > 0)
					{
						var contact = list_Finance[0] as CustomerContact;
						cells[rowIndex, 11].PutValue(contact.Name);
						cells[rowIndex, 12].PutValue(contact.Telephone);
					}
					cells[rowIndex, 11].SetStyle(cellStyles[11]);
					cells[rowIndex, 12].SetStyle(cellStyles[12]);
					if (!customer.TermsOfPayment.IsNullOrWhiteSpace())
					{
						if (customer.TermsOfPayment.Equals("到付"))
						{
							cells[rowIndex, 13].PutValue("√");
							cells[rowIndex, 14].PutValue(String.Empty);
						}
						if (customer.TermsOfPayment.Equals("预付"))
						{
							cells[rowIndex, 13].PutValue(String.Empty);
							cells[rowIndex, 14].PutValue("√");
						}
						if (customer.TermsOfPayment.Equals("到付和预付"))
						{
							cells[rowIndex, 13].PutValue("√");
							cells[rowIndex, 14].PutValue("√");
						}
					}
					cells[rowIndex, 13].SetStyle(cellStyles[13]);
					cells[rowIndex, 14].SetStyle(cellStyles[14]);
					cells[rowIndex, 15].PutValue(String.Empty);
					cells[rowIndex, 15].SetStyle(cellStyles[15]);
					if (customer.RewardSituation)
					{
						cells[rowIndex, 16].PutValue("是");
						cells[rowIndex, 16].SetStyle(cellStyles[16]);
					}
					else
					{
						cells[rowIndex, 16].PutValue("否");
						cells[rowIndex, 16].SetStyle(cellStyles[16]);
					}
					var invoicesituation = ((InvoiceSituation)customer.InvoiceSituation);
					String sinvoicesituation = "";
					switch (invoicesituation)
					{
						case InvoiceSituation.是:
							sinvoicesituation = "是";
							break;

						case InvoiceSituation.否:
							sinvoicesituation = "否";
							break;

						case InvoiceSituation.无需开发票:
							sinvoicesituation = "无需开发票";
							break;

						default:
							break;
					}
					cells[rowIndex, 17].PutValue(sinvoicesituation);
					cells[rowIndex, 17].SetStyle(cellStyles[17]);
					cells[rowIndex, 18].PutValue(customer.CustomerAgreement);
					cells[rowIndex, 18].SetStyle(cellStyles[18]);
					cells[rowIndex, 19].PutValue(String.Empty);
					cells[rowIndex, 19].SetStyle(cellStyles[19]);
					cells[rowIndex, 20].PutValue(customer.PaymentCycle);
					cells[rowIndex, 20].SetStyle(cellStyles[20]);
					if (customer.DevelopmentDate > DateTime.MinValue)
					{
						cells[rowIndex, 21].PutValue(customer.DevelopmentDate.ToString("yyyy-MM-dd"));
					}
					cells[rowIndex, 21].SetStyle(cellStyles[21]);
					foreach (var staff in StaffList)
					{
						if (staff.ID == customer.StaffID)
						{
							cells[rowIndex, 22].PutValue(staff.FullName);
							break;
						}
					}
					cells[rowIndex, 22].SetStyle(cellStyles[22]);
					rowIndex++;
					id++;
				}
			}

			sourceBook.Save(PathHelper.PathCombineFix(Path, file));
		}

		#endregion

		private Int32 SelectCustomer = 0;
		private String FilePath = "";

		private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
		{
			try
			{
				Export("客户备案明细表", FilePath);
			}
			catch (Exception ex) { ProcessException(ex); }
		}

		private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
		{
		}

		private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			this.BeginInvoke(new MethodInvoker(() =>
			{
				DialogHelper.ShowMessage("导出", eTaskDialogIcon.Information2, "客户备案明细表导出完成！", null, eTaskDialogButton.Ok);
				btnExport.Enabled = true;
				btnClose.Enabled = true;
			}));
		}

		/// <summary>
		/// 导出按钮事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnExport_Click(object sender, EventArgs e)
		{
			if (txtFolder.Text.IsNullOrWhiteSpace())
			{
				DialogHelper.ShowWarning(null, "请选择报表存储路径！");
				return;
			}
			if (backgroundWorker1.IsBusy != true)
			{
				btnExport.Enabled = false;
				btnClose.Enabled = false;
				SelectCustomer = Convert.ToInt32(frmcustomer.SelectedValue);
				FilePath = txtFolder.Text.Trim();
				backgroundWorker1.RunWorkerAsync();
			}
		}

		/// <summary>
		/// 文件浏览事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnBrowse_Click(object sender, EventArgs e)
		{
			var fbg = new FolderBrowserDialog();
			DialogResult dr = fbg.ShowDialog(this);
			if (dr == DialogResult.OK)
			{
				txtFolder.Text = fbg.SelectedPath;
			}
		}

		/// <summary>
		/// 关闭按钮事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnClose_Click(object sender, EventArgs e)
		{
			this.DialogResult = DialogResult.Cancel;
			this.Close();
		}
	}
}